/**
 * 图片压缩模块
 * @Created by li-rz on 16-9-14.
 */
const fs = require('fs');
const path = require('path');
const ReadStream = fs.ReadStream;
const gm = require('gm').subClass({imageMagick: true});
const IMAGE_QUALITY = 30;

/**
 * 获取临时文件夹
 * @param image_name
 * @param output_path
 * @return {Path}
 */
function getTempPath (image_name, output_path) {
    return isPNGorBMP(image_name) || isGIF(image_name) ?
        path.join(output_path, getFileName(image_name) + '.jpg') :
        path.join(output_path, image_name);
}

/**
 * 获取图片文件流或者路径
 * @param image_path
 * @param image_name
 * @return {ReadStream} or {Path}
 */
function getImageBuffer (image_path, image_name) {
    return isGIF(image_name) ?
        path.join(image_path, image_name) :
        fs.createReadStream(path.join(image_path, image_name));
}

/**
 * 压缩图片,支持jpg, bmp, png, gif(只有第一帧), 用于压缩图片质量
 * @param image_path - 存放图片的文件夹绝对路径
 * @param image_name - 图片名
 * @param output_path - 输出的文件夹绝对路径
 * @param quality - 图片质量 [0 - 100]
 */
var compressImage = (image_path, image_name, output_path, quality) => {
    if (!quality || quality > 100 || quality < 0) {
        quality = IMAGE_QUALITY;
    }

    // 输出的图片
    let temp_path = getTempPath(image_name, output_path);

    let buffer = isGIF(image_name) ?
        path.join(image_path, image_name) :
        fs.createReadStream(path.join(image_path, image_name));

    writeImage(buffer, temp_path, quality);
};

/**
 * 缩放图片大小
 * @param image_path - 原图片地址
 * @param image_name - 原图片名
 * @param output_path - 输出图片地址
 * @param size - 缩放大小
 */
var resizeImage = (image_path, image_name, output_path, size) => {
    if (!size) {
        size = {width: 80, height: 80};
    }
    let temp_path = getTempPath(image_name, output_path);
    let buffer = getImageBuffer(image_path, image_name);

    if (!(buffer instanceof ReadStream)) {
        buffer = buffer + '[0]';
    }

    gm(buffer)
        .resize(size.width, size.height)
        .write(temp_path, function (err) {
            if(err) {
                throw Error(err);
            }
        });
};

/**
 * 获取文件名
 * @param file
 * @returns {String} file name
 */
function getFileName (file) {
    return path.basename(file, path.extname(file));
}

/**
 * 判断是否为PNG格式或者BMP格式图片
 * @param img - 图片文件路径
 * @returns {boolean}
 */
function isPNGorBMP (img) {
    return path.extname(img) === '.png' || path.extname(img) === '.bmp';
}

/**
 * 判断是否为GIF格式图片
 * @param img - 图片文件路径
 * @returns {boolean}
 */
function isGIF (img) {
    return path.extname(img) === '.gif';
}

function writeImage (buffer, temp_path, quality) {
    if (!(buffer instanceof ReadStream)) {
        buffer = buffer + '[0]';
    }
    gm(buffer)
        .quality(quality)
        .write(temp_path, function (err) {
            if (err) {
                throw Error(err);
            }
        })
}

module.exports = {
    compressImage: compressImage,
    resizeImage: resizeImage
};